package com.zmjmall.demo.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zmjmall.demo.api.ProductService;
import com.zmjmall.demo.dao.ProductMapper;
import com.zmjmall.demo.dao.SkuProductMapper;
import com.zmjmall.demo.dto.ProductDTO;
import com.zmjmall.demo.model.Product;
import com.zmjmall.demo.model.ProductAttrbute;
import com.zmjmall.demo.model.ProductProperty;
import com.zmjmall.demo.model.SkuProduct;
import com.zmjmall.demo.repository.ProductAttrbuteRepository;
import com.zmjmall.demo.repository.ProductPropertyRepository;
import com.zmjmall.demo.repository.ProductRepository;
import com.zmjmall.demo.util.Descartes;
import com.zmjmall.demo.util.SKUGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zmj
 * @version 2018/6/29
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private SkuProductMapper skuProductMapper;

    @Autowired
    private ProductAttrbuteRepository productAttrbuteRepository;

    @Autowired
    private ProductPropertyRepository productPropertyRepository;

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }
    @Override
    public Product findById(String id) {
        return productRepository.findByIdEquals(id);
    }

    @Override
    public Page<Product> findAllByPage(Pageable pageable) {
        log.info(" \n 分页查询用户："
                + " PageNumber = " + pageable.getPageNumber()
                + " PageSize = " + pageable.getPageSize());
        return productRepository.findAll(pageable);
    }

    @Override
    public List<Product> findAllPage(int pageNum, int pageSize,String sort) {
        PageHelper.startPage(pageNum,pageSize,sort);
        List<Product> list = productMapper.findAllPage();
        return list;
    }

    @Override
    @Transactional
    public int insert(ProductDTO productDTO) {
        Product product = new Product();

        //创建商品基本信息
        BeanUtils.copyProperties(productDTO,product);
        //设置主键id
        product.setId(com.baomidou.mybatisplus.toolkit.IdWorker.getIdStr());
        int i = productMapper.insertSelective(product);

        /**
         * 解析 attributeValues
         * attributeValues : “属性id1:属性值id1/属性值id2,属性id12:属性值id1/属性值id2,”
         * 例  attributeValues = "11(尺码id):3/4,12(颜色ID):1/2"
         */
        String[] attributeValues = productDTO.getAttributeValues().split(",");
        Map<String, String> attributeMap = autoMap(attributeValues);

        List<ProductAttrbute> productAttrbutes = productAttrbuteRepository.findAll();
        List<ProductProperty> productProperties = productPropertyRepository.findByCategoryId(product.getCategoryId());

        List<List<String>> list = new ArrayList<>();
        JSONArray baseArray = new JSONArray();
        for(Map.Entry<String, String> entry: attributeMap.entrySet()){
            JSONObject baseObject = new JSONObject();
            String[] split = entry.getValue().split("/");
            JSONArray attrbutes = new JSONArray();
            for (String  id:split) {
                JSONObject object = new JSONObject();
                object.put("attributeId",id);
                for (ProductAttrbute productAttrbute:productAttrbutes) {
                    if(productAttrbute.getId().equals(id)) {
                        object.put("attributeName",productAttrbute.getAttributeName());
                    }
                }
                attrbutes.add(object);
            }
            baseObject.put("id",entry.getKey());
            for (ProductProperty productProperty:productProperties) {
                if(productProperty.getId().equals(entry.getKey())) {
                    baseObject.put("propertyName",productProperty.getPropertyName());
                }
            }
            baseObject.put("attrbutes",attrbutes);
            baseArray.add(baseObject);

            list.add(Arrays.asList(split));
        }

        List<List<String>> recursiveResult = new ArrayList<List<String>>();
        // 递归实现笛卡尔积
        Descartes.recursive(list, recursiveResult, 0, new ArrayList<String>());

        for (List<String> lists : recursiveResult) {
            JSONArray array = new JSONArray();
            String attributeIds = "";
            String attributeNames = "";

            for (String string : lists) {
                JSONObject object = new JSONObject();
                object.put("attributeId",string);
                attributeIds +=  string + "/";
                for (ProductAttrbute productAttrbute:productAttrbutes) {
                    if(productAttrbute.getId().equals(string)) {
                        object.put("attributeName",productAttrbute.getAttributeName());
                        attributeNames += productAttrbute.getAttributeName() + "-";
                    }
                }
                for (ProductAttrbute productAttrbute:productAttrbutes) {
                    if(productAttrbute.getId().equals(string)) {
                        for (ProductProperty productProperty:productProperties) {
                            if(productProperty.getId().equals(productAttrbute.getPropertyId())) {
                                object.put("propertyName",productProperty.getPropertyName());
                            }
                        }
                    }
                }
                array.add(object);
            }

            SkuProduct skuProduct = new SkuProduct();

            //设置主键id
            skuProduct.setId(com.baomidou.mybatisplus.toolkit.IdWorker.getIdStr());
            skuProduct.setProductId(product.getId());

            //生成sku
            skuProduct.setSku(SKUGenerator.createSKU(product.getShopId(),product.getCategoryId()
                    ,product.getId(),SKUGenerator.attributesASC(attributeIds)));

            //产品标题追加属性
            skuProduct.setSkuProductName(SKUGenerator.nameSpilt(product.getProductName() + "  " + attributeNames));
            //产品副标题默认
            skuProduct.setTitle(skuProduct.getSkuProductName());
            //设置属性
            skuProduct.setAttributeValues(array.toJSONString());

            skuProductMapper.insert(skuProduct);
        }
        return i;
    }

    @Override
    public void delete(String id) {

    }

    private Map<String,String> autoMap(String[] ids){
        HashMap<String,String> map = new HashMap<>();
        for (String p: ids) {
            String[] split = p.split(":");
            map.put(split[0],split[1]);
        }
        return map;
    }
}
